package DataLayer.DB;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import DataLayer.Model.Land;

public class DBLand
{
	private Connection con = DBConnection.getInstance().getDBcon();

	public ArrayList<Land> getAllLande()
	{
		return miscWhere("");
	}

	public Land getLand(int landId)
	{
		return singleWhere("landId = " + landId);
	}

	public Land getLand(String land)
	{
		return singleWhere("land = '" + land + "'");
	}

	private ArrayList<Land> miscWhere(String wClause)
	{
		ResultSet results;
		ArrayList<Land> list = new ArrayList<Land>();
		String query = buildQuery(wClause);
		query += " ORDER by land";
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			while (results.next())
			{
				Land l = new Land();
				l = buildLand(results);
				list.add(l);
			}
			stmt.close();
		}
		catch (Exception e)
		{
			System.out.println("Query exception - select: " + e);
			e.printStackTrace();
		}
		return list;
	}

	private Land singleWhere(String wClause)
	{
		ResultSet results;
		Land l = null;
		String query = buildQuery(wClause);
		System.out.println(query);
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			if (results.next())
			{
				l = buildLand(results);
				stmt.close();
			}
			else
			{
				l = null;
			}
		}
		catch (Exception e)
		{
			System.out.println("Query exception: " + e);
		}
		return l;
	}

	private String buildQuery(String wClause)
	{
		String query = "SELECT land, landid FROM land ";
		if (wClause.length() > 0)
		{
			query += "WHERE " + wClause;
		}
		return query;
	}

	private Land buildLand(ResultSet results)
	{
		Land l = new Land();
		try
		{
			l.setLand(results.getString("land"));
			l.setLandId(results.getInt("landid"));
		}
		catch (Exception e)
		{
			System.out.println("error in building the Land object");
		}
		return l;
	}
}
